package com.rbn.stockmobiledevices.admin;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.rbn.stockmobiledevices.utils.UploadItem;

@Controller
public class AdminController {
	private static final Logger logger = Logger.getLogger(AdminController.class);
	private AdminManager adminManager;
	
	@RequestMapping(method = RequestMethod.POST)
    public String importDbFile(UploadItem uploadItem) {
		logger.info("IN > importDbFile");
	    try {
            MultipartFile file = uploadItem.getFileData();
            InputStream inputStream = null;
            if (file.getSize() > 0) {
                inputStream = file.getInputStream();
            }
            adminManager.importDbData(inputStream);
	    } catch (Exception e) {
            e.printStackTrace();
	    }finally{
	    	logger.info("OUT < importDbFile");
	    }
	    return "admin.tiles";
    }
	
	@RequestMapping(value = "/exportDb", method = RequestMethod.GET)
    public String downloadFile(HttpServletResponse resp)
        throws IOException {
        
		logger.info("IN > downloadFile");
		try{
        resp.setHeader("Content-Disposition","attachment; filename=\"stock_export.xml\"");
        OutputStream out = resp.getOutputStream();
        resp.setContentType("text/plain; charset=utf-8");
        
        try {
			adminManager.exportDbData(out);
		} catch (SQLException e) {
			e.printStackTrace();
		}
        
        out.flush();
        out.close();
		}finally{
			logger.info("OUT < downloadFile");
		}
        
        return null;
    }

	@Autowired
	public AdminController(AdminManager adminManager) {
		this.adminManager = adminManager;
	}
	
	@RequestMapping(value = "/administracion", method = RequestMethod.GET)
	public String proveedorList(Model model) {
		return "admin.tiles";
	}
	
	@RequestMapping(value = "/getDbStatus", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getDbStatus(){
		logger.info("IN > getDbStatus");		
		try{
			Map<String, Object> resultado = new HashMap<String, Object>();
			boolean status = false;
			String mensaje="";
			try {
				Map<String, String> conf = adminManager.getDbConfiguration();
				if(conf==null){
					mensaje="No se puede acceder al motor de base de datos. Verifique la configuracion de base de datos o que el servicio este corriendo.";
				}else{
					String url = conf.get(AdminManager.DB_INFORMATION_JDBC_URL);
					String usuario = conf.get(AdminManager.DB_INFORMATION_JDBC_USUARIO);
					String password = conf.get(AdminManager.DB_INFORMATION_JDBC_PASSWORD);
					String dbName = conf.get(AdminManager.DB_INFORMATION_JDBC_DBNAME);
					try{
						status=adminManager.dbIsCreated(url, usuario, password, dbName);
						resultado = adminManager.getDbInformation(url, usuario , password, dbName);
						resultado.put("DBNAME", dbName);
						if(status){
							mensaje = "La base esta creada correctamente";
						}else{
							mensaje = "La base de datos \"<b>" + dbName + "</b>\" no existe, Verifique las opciones para re-crear la base de datos y para importar datos.<br/>";
						}
					}catch(SQLException e){
						mensaje = "Error al intentar acceder al motor de base de datos verifique que el usuario tenga permisos o que la configuracion sea correcta";
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				mensaje = "Error inesperado!!!";
			}
			resultado.put("status", status);
			resultado.put("mensaje", mensaje);
			return resultado;
		}finally{
			logger.info("OUT < getDbStatus");
		}
	}
	
	@RequestMapping(value = "/createDb", method = RequestMethod.GET)
	public String createDb(){
		logger.info("IN > createDb");
		try{
			adminManager.createDB();
		}finally{
			logger.info("OUT < createDb");
		}
		return "admin.tiles";
	}
}